package cn.broadin.app.hotel.util;

import android.os.AsyncTask;
import android.view.View;

/**
 * .9图飞框动画
 * 
 * @author long
 * @version 1.0.0
 * @date 2015年12月4日下午5:04:16
 */
public class TvAnimator extends AsyncTask<Void, Integer, Integer> {

	private static final int durationTranslate = 9;

	private View target;
	private int l, t, cl, ct;
	private int width, cwidth, height, cheight;
	private int dX, dY, dW, dH;
	private int frequence = 17;

	public TvAnimator(View target, View item) {
		this.target = target;
	}

	public void setTargetParams(int l, int t, int width, int height) {
		this.l = l;
		this.t = t;
		this.width = width;
		this.height = height;
		this.cl = target.getLeft();
		this.ct = target.getTop();
		this.cwidth = target.getWidth();
		this.cheight = target.getHeight();
	}

	/** 
         * 
         */
	@Override
	protected void onPreExecute() {

		dW = (int) (width - cwidth > 0 ? Math.ceil((width - cwidth)
				/ (frequence * 1.0)) : Math.floor((width - cwidth)
				/ (frequence * 1.0)));
		dH = (int) (height - cheight > 0 ? Math.ceil((height - cheight)
				/ (frequence * 1.0)) : Math.floor((height - cheight)
				/ (frequence * 1.0)));
		dX = (int) (l - cl > 0 ? Math.ceil((l - cl) / (frequence * 1.0)) : Math
				.floor((l - cl) / (frequence * 1.0)));
		dY = (int) (t - ct >= 0 ? Math.ceil((t - ct) / (frequence * 1.0))
				: Math.floor((t - ct) / (frequence * 1.0)));

		// Log.e(VIEW_LOG_TAG, cl + "---" + l + "---" + ct + "---" + t
		// + "====" + dX + ":" + dY + ":" + dW + ":" + dH + "---"
		// +durationTranslate);
	}

	/** 
         * 
         */
	@Override
	protected Integer doInBackground(Void... params) {

		while (cl != l || t != ct || cwidth != width || cheight != height) {

			if (Math.abs(cl - l) <= Math.abs(dX)) {
				cl = l;
			} else {
				cl += dX;
			}

			if (Math.abs(ct - t) <= Math.abs(dY)) {
				ct = t;
			} else {
				ct += dY;
			}

			if (Math.abs(width - cwidth) <= Math.abs(dW)) {
				cwidth = width;
				dW = 0;
			} else {
				cwidth += dW;
			}

			if (Math.abs(height - cheight) <= Math.abs(dH)) {
				cheight = height;
				dH = 0;
			} else {
				cheight += dH;
			}

			// Log.e(VIEW_LOG_TAG, cl+"=="+ct+"=="+(cl + cwidth + dW)+"=="+(ct +
			// cheight + dH));

			publishProgress(cl, ct, cl + cwidth + dW, ct + cheight + dH);
			try {
				Thread.sleep(durationTranslate);
			} catch (InterruptedException e) {
			}
		}

		return null;
	}

	/** 
         * 
         */
	@Override
	protected void onPostExecute(Integer integer) {

	}

	/** 
         * 
         */
	@Override
	protected void onProgressUpdate(Integer... values) {
		target.layout(values[0], values[1], values[2], values[3]);
	}
}